<?php

namespace Frieza\Modules\Push\Controllers;

use App\Admin\Extensions\Tools\UserButton;
use App\Exceptions\InputErrorException;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\AdmPush\AdmPushTask as mAdmPushTask;
use Doraemon\model\AdmPush\AdmPushTaskGroup as mAdmPushTaskGroup;
use Doraemon\model\AdmPush\ScenePushTask;
use Doraemon\model\Position\PositionRules;
use Doraemon\service\AdmPush\PushTask;
use Doraemon\service\position\UserProfileModule;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form\Field\Table;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Doraemon\tools\ImgUrl;

class ScenePushController extends Controller
{

    const PAGE_SIZE = 20;



    public function index(Request $request, Content $content)
    {
        $requestParams = $request->all();
        $list = ScenePushTask::selectByWhere(['status'=>0, 'pid' => 0]);
        $taskCondition = [];
        $gridModel = new pGridDataModel($list, $total = 0);
        $grid = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableFilter();
                $grid->disablePagination();
                $grid->paginate($gridModel->getPerPage());
                $grid->column('id', '记录id')->width(80);
                $grid->column('push_type', '推送类型')->width(200);
                $grid->column('push_id', '(push ID)')->width(200);
                $grid->column('push_time', '发送时间')->width(150);
                $grid->column('admin_id', '操作人')->display(function () {
                    return $this->admin_id ? Admin::user()->find($this->admin_id)->name : '-';
                })->width(100);
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableDelete();
                    $actions->disableView();
                });

            }
        );
        return $content
            ->header('场景push任务列表')
            ->description(' ')
            ->breadcrumb(['text' => '场景push任务列表'])
            ->row($grid);
    }


    public function create(Request $request, Content $content, $id = 0)
    {
        $header = $id ? '编辑推送任务' : '添加推送任务';
        $list = $id ? ScenePushTask::selectByWhere(['OR' => ['id' => $id, 'pid' => $id], 'status' => 0]) : [];
        $pool = [];
        $info = [];
        foreach ($list as $v) {
            if ($v['pid'] == 0) {
                $info = $v;
            } else {
                $pool[] = [
                    $v['category'],
                    $v['push_title'],
                    $v['jump_type'],
                    $v['jump'],
                ];
            }
        }
        if (!empty($info)) $info['push_data'] = $pool;

        $form = new Form($info);
        $form->hidden('id');
        $form->text('push_type',"推送类型")->required();
        $form->text('push_id',"push ID")->required();
        $form->time('push_time')->required();
        if ($id && $pool) {
            $form->display('push_data', '内容池数据')->with(function ($value) {
                return (new \Encore\Admin\Widgets\Table(['品类', 'push标题', '落地页类型', '落地页'], $value))->render();
            });
        }
        $form->file('push_file', '内容池数据来源');
        $form->action(url('admin/push/ScenePush/save'));
        return $content->header($header)->breadcrumb(
            ['text' => '场景push任务列表', 'url' => url('admin/push/ScenePush/list')],
            ['text' => $header])
            ->row($form);
    }

    public function save(Request $request, Content $content)
    {
        try {
            $id = $request->input("id", "");
            $push_type = $request->input("push_type", "");
            $push_id = $request->input('push_id', "");
            $push_time = $request->input('push_time', "");
            $file = $request->file("push_file");
            $rowData = [];
            if ($file) {
                $inputFileType = \PHPExcel_IOFactory::identify($file);
                $objReader = \PHPExcel_IOFactory::createReader($inputFileType);
                $objExcel = $objReader->load($file);
                $sheet = $objExcel->getSheet();
                $rowNum = $sheet->getHighestRow();
                $columnNum = $sheet->getHighestColumn();
                $rowData = $sheet->rangeToArray('A2:' . $columnNum . ($rowNum), NULL, TRUE, FALSE);
            }
            $data = [
                'push_type' => $push_type,
                'push_id' => $push_id,
                'push_time' => $push_time,
                'admin_id' => Admin::user()->id,
            ];
            $pushData = [];
            foreach ($rowData as $i => $v) {
                $i = $i + 2;
                $category = trim($v[0]);
                $push_title = trim($v[1]);
                $jump_type = trim($v[2]);
                $jump = trim($v[3]);
                if (empty($category) && empty($push_title) && empty($jump_type) && empty($jump)) continue;
                //'品类', 'push标题', '落地页类型', '落地页'
                if (empty($category)) throw new \Exception("表格第[$i]行 品类为空");
                if (empty($push_title)) throw new \Exception("表格第[$i]行 push标题为空");
                if (empty($jump_type)) throw new \Exception("表格第[$i]行 落地页类型为空");
                if (empty($jump)) throw new \Exception("表格第[$i]行 落地页为空");
                $pushData[] = $data + [
                        'pid' => &$pid,
                        'category' => $category,
                        'push_title' => $push_title,
                        'jump_type' => $jump_type,
                        'jump' => $jump,
                    ];
            }

            if ($id) {
                $del = false;
                if (!is_null($file)) $del = true;
                if ($del) ScenePushTask::updateData(['status' => 9], ['pid' => $id, 'status' => 0]);
                ScenePushTask::updateData($data, ['id' => $id]);
                $pid = $id;
            } else {
                $pid = ScenePushTask::insertData($data);
                if (empty($pid))  throw new \Exception("数据保存失败");
            }

            foreach ($pushData as $v) {
                ScenePushTask::insertData($v);
            }

            $success = new MessageBag([
                'title' => '操作成功'
            ]);
            return redirect(url('admin/push/ScenePush/list'))->with(compact('success'));
        } catch (\Exception $e) {
            \Doraemon\tools\Log::debug($e->getMessage());
            $error = new MessageBag([
                'title' => '操作失败,信息:' . $e->getMessage()
            ]);
            return back()->withInput()->with(compact('error'));
        }
    }



}
